<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <h3>聊天内容:</h3>
    <textarea id="content" style="height: 200px; width:400px;"></textarea>
    <br/>
    <input type="text" id="sendMsg" />
    <button id="btn_send">发送</button>

    <script src="/socket.io/socket.io.js"></script>

    <script>
        var content = document.getElementById('content');
        var sendMsg = document.getElementById('sendMsg');
        var btn_send = document.getElementById('btn_send');

        var socket = io.connect('http://localhost:8888');

        socket.on('receiveMsg', function (data) {
            content.value += data.name+':'+data.chatInfo+' '+data.time+'\n';
        });

        socket.on('enter', function (data) {
            content.value += data.name + data.info + ' ' + data.time + '\n';
        });

        socket.on('leaved', function (data) {
            content.value += data.info + ' ' + data.time + '\n';
        });

        btn_send.addEventListener('click', function () {
            var data = { name: '客户端1', chatInfo: sendMsg.value, time: new Date().toLocaleString() };
            socket.emit('sendMsg', data);
            content.value += data.name + ':' + data.chatInfo + ' ' + data.time + '\n';
            sendMsg.value = '';
        })

        socket.on('connect',function() {
            var data = { name:'客户端1',info:'进入了聊天室', time: new Date().toLocaleString() }
            socket.emit('login', data);
        })
    </script>
</body>

</html>